const fs = require('fs');
const path = require('path');
const fse = require('fs-extra');

/**
 * 递归扫描并提取特定类型文件
 * @param {string} sourceDir - 源目录
 * @param {string} ext - 目标扩展名（如 .mp4）
 * @param {string} outputDir - 输出目录
 * @param {string[]} ignoreDirs - 要忽略的文件夹名称数组
 */
async function extractFilesByExt(sourceDir, ext, outputDir, ignoreDirs = []) {
  const files = [];

  function walk(dir) {
    const items = fs.readdirSync(dir);
    for (const item of items) {
      const fullPath = path.join(dir, item);
      const stat = fs.statSync(fullPath);

      // 跳过忽略的文件夹
      if (stat.isDirectory() && ignoreDirs.includes(item)) {
        continue;
      }

      if (stat.isDirectory()) {
        walk(fullPath);
      } else if (stat.isFile() && path.extname(fullPath).toLowerCase() === ext.toLowerCase()) {
        files.push(fullPath);
      }
    }
  }

  walk(sourceDir);

  await fse.ensureDir(outputDir);

  for (const filePath of files) {
    const baseName = path.basename(filePath);
    let targetPath = path.join(outputDir, baseName);
    let count = 1;
    while (fs.existsSync(targetPath)) {
      const { name, ext } = path.parse(baseName);
      targetPath = path.join(outputDir, `${name}_${count}${ext}`);
      count++;
    }
    await fse.copy(filePath, targetPath);
  }

  console.log(`✅ 提取完成，共复制 ${files.length} 个文件到 ${outputDir}`);
}

module.exports = extractFilesByExt;
